//
//  File.swift
//
//
//  Created by didi on 2022/9/21.
//

import SwiftHtml
import Vapor

public struct SelectGroupFieldTemplate: TemplateRepresentable {
    public var context: SelectGroupFieldContext

    public init(_ context: SelectGroupFieldContext) {
        self.context = context
    }

    @TagBuilder
    public func render(_ req: Request) -> Tag {
        LabelTemplate(context.label).render(req)

        Select {
            for group in context.options {
                Optgroup {
                    for item in group.options {
                        Option(item.label)
                            .value(item.key)
                            .label(item.label)
                            .selected(context.value == item.key)
                    }
                }
                .label(group.name)
            }
        }
        .name(context.key)

        if let error = context.error {
            Span(error)
                .class("error")
        }
    }
}
